﻿// Please see documentation at https://docs.microsoft.com/aspnet/core/client-side/bundling-and-minification
// for details on configuring this project to bundle and minify static web assets.

///初始化区域
function InitRegion(regionContainer) {
    if (!regionContainer.hasClass("select2-region-group")) {
        return false;
    }
    var $inputValue = regionContainer.children(regionContainer.attr("data-bind-input"));//设置或获取选中的值
    var dataLevel = regionContainer.attr("data-bind-level");
    if (!dataLevel || dataLevel == "" || parseInt(dataLevel) <= 0)
    {
        dataLevel = 3;
    }
    var regionid = $inputValue.val();
    if (!regionid || regionid == " ") {
        regionid = 0;
    }
    var currItem2, currItem3, index = 0;// 二级 三级 项集合
    var data_Item1_value,
    data_Item2_value,
    data_Item3_value = { RegionId: regionid };//每一级的选择值
    $.each(Global_Region_Data, function (ins1, item1) {//查找并获取每一级的值
        var item1flag = false;
        if (item1.ChildEntities != null && item1.ChildEntities.length > 0) {
            $.each(item1.ChildEntities, function (ins2, item2) {
                var item2flag = false;
                if (item2.ChildEntities != null && item2.ChildEntities.length > 0) {
                    $.each(item2.ChildEntities, function (ins3, item3) {
                        if (data_Item3_value.RegionId == item3.RegionId) {
                            item2flag = true;
                            data_Item3_value = item3;
                            return false;
                        }
                    });

                }
                if (item2flag) {
                    data_Item2_value = item2;
                    item1flag = true;
                    return false;
                }
                else {
                    if (item2.RegionId == data_Item3_value.RegionId) {
                        data_Item2_value = item2;
                        item1flag = true;
                        return false;
                    }
                }
            });
        }
        if (item1flag) {
            data_Item1_value = item1;
            return false;
        }
        else {
            if (dataLevel == 1)
            {
                if (item1.RegionId == data_Item3_value.RegionId) {
                    data_Item1_value = item1;
                    item1flag = true;
                    return false;
                }
            }
        }
    });

    regionContainer.find("select").each(function () {
        var _self = $(this);
        index = index + 1;
        _self.attr("id", "select2-region-group-item-" + index);
        _self.attr("tab-index", index);
        
        _self.select2({
            delay: 250,
            // minimumInputLength: 1,
            ajax: {
                url: "/static/cloud/config/region/region.json",
                dataType: "json",
                type: "get",
                cache: true,
                data: function (params) {
                    return {
                        q: params.term
                    };
                },
                processResults: function (result, params) {
                    result = Global_Region_Data;
                    var filter = [{ id: " ", text: "不限" }];
                    if (parseInt(_self.attr("tab-index")) == 1)
                    {
                        if (dataLevel == 1)
                        {
                            filter=[{ id: "0", text: "不限" }];
                        }
                        
                    }
                    
                    if (parseInt(_self.attr("tab-index")) >= 2) {
                        var childentities = [];
                        if (parseInt(_self.attr("tab-index")) == 2) {
                            childentities = currItem2;
                        }
                        else {
                            childentities = currItem3;
                        }
                        if (childentities && childentities.length > 0) {
                            for (var i = 0; i < childentities.length; i++) {
                                if (!params.term || params.term == "" || (
                                params.term != "" && (childentities[i].RegionName.indexOf(params.term) >= 0
                                || childentities[i].RegionNameEn.indexOf(params.term) >= 0
                                || childentities[i].RegionShortNameEn.indexOf(params.term) >= 0))) {
                                    filter.push(childentities[i]);
                                }
                            }
                        }

                    }
                    else {
                        for (var i = 0; i < result.length; i++) {
                            if (result[i].ParentId > 0
                                && result[i].RegionLevel == parseInt(_self.attr("tab-index"))
                                && (!params.term || params.term == "" || (
                               params.term != "" && (result[i].RegionName.indexOf(params.term) >= 0
                                || result[i].RegionNameEn.indexOf(params.term) >= 0
                                || result[i].RegionShortNameEn.indexOf(params.term) >= 0)))) {

                                filter.push(result[i]);
                            }
                        }
                    }
                    return {
                        results: filter,

                    };
                }
            },
            placeholder: (index == 1 ? "===省份===" : (index == 2 ? "===输入市===" : "===输入县===")),
            allowClear: true,    //选中之后，可手动点击删除
            escapeMarkup: function (markup) { return markup; }, // 字符转义处理自定义格式化防止xss注入
          
            templateSelection: function (repo) {
                
                return repo.text;
            } // 函数用于呈现当前的选择

        });
        _self.on("select2:select", function (e) {
            $inputValue.val("");
            var selectResult = e.params.data;
            if (_self.attr("tab-index") == "1") {
                regionContainer.find("#select2-region-group-item-2").val("");
                regionContainer.find("#select2-region-group-item-2").trigger("change");
                regionContainer.find("#select2-region-group-item-3").val("");
                regionContainer.find("#select2-region-group-item-3").trigger("change");
                regionContainer.find("#select2-region-group-item-2").hide();
                regionContainer.find("#select2-region-group-item-2").next().hide();
                regionContainer.find("#select2-region-group-item-3").hide();
                regionContainer.find("#select2-region-group-item-3").next().hide();
                currItem2 = null;
                if (selectResult && selectResult.id != " ") {
                    regionContainer.find("#select2-region-group-item-2").show();
                    regionContainer.find("#select2-region-group-item-2").next().show();
                    currItem2 = selectResult.ChildEntities;
                    
                }
                if (dataLevel == 1)
                {
                    $inputValue.val(selectResult.id);
                }
                currItem3 = null;
            }
            else if (_self.attr("tab-index") == "2") {
                currItem3 = null;
                regionContainer.find("#select2-region-group-item-3").val("");
                regionContainer.find("#select2-region-group-item-3").trigger("change");
                if (selectResult && selectResult.id != " " && selectResult.ChildEntities != null && selectResult.ChildEntities.length > 0) {
                    regionContainer.find("#select2-region-group-item-3").show();
                    regionContainer.find("#select2-region-group-item-3").next().show();
                    currItem3 = selectResult.ChildEntities;
                }
               
                else {
                    $inputValue.val(selectResult.id);
                }
                if (dataLevel == 1) {
                    $inputValue.val(selectResult.id);
                }
            }
            else {
                $inputValue.val(selectResult.id);
            }
        });

        if (parseInt(_self.attr("tab-index")) == 1) {
            if (data_Item1_value && data_Item1_value.id && data_Item1_value.id != " ") {
                _self.append("<option value='" + data_Item1_value.id + "'>" + data_Item1_value.text + "</option>");
                currItem2 = data_Item1_value.ChildEntities;
                _self.trigger("change");
                return;
            }
        }
        else if (parseInt(_self.attr("tab-index")) == 2) {
            if (data_Item2_value && data_Item2_value.id && data_Item2_value.id != " ") {
                _self.show();
                _self.next().show();
                _self.append("<option value='" + data_Item2_value.id + "'>" + data_Item2_value.text + "</option>");
                currItem3 = data_Item2_value.ChildEntities;
                _self.trigger("change");
            }
        }
        else if (parseInt(_self.attr("tab-index")) == 3) {
            if (data_Item3_value && data_Item3_value.id && data_Item3_value.id != " " && data_Item2_value.id != data_Item3_value.id) {
                _self.show();
                _self.next().show();
                _self.append("<option value='" + data_Item3_value.id + "'>" + data_Item3_value.text + "</option>");
                _self.trigger("change");
            }

        }
        var value = _self.val();
        if (index > 1 && (!value || value == "")) {

            _self.css({ "display": "none" });
            _self.next().css({ "display": "none" });
        }

    });
}

// Write your JavaScript code.
var CONSTANT = {
   
    // datatables常量
    DATA_TABLES: {
        DEFAULT_OPTION: { // DataTables初始化选项
            LANGUAGE: {
                sProcessing: "处理中...",
                sLengthMenu: "显示 _MENU_ 项结果",
                sZeroRecords: "没有匹配结果",
                sInfo: "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
                sInfoEmpty: "显示第 0 至 0 项结果，共 0 项",
                sInfoFiltered: "(由 _MAX_ 项结果过滤)",
                sInfoPostFix: "",
                sSearch: "搜索:",
                searchPlaceholder: "关键字搜索",
                sUrl: "",
                sEmptyTable: "表中数据为空",
                sLoadingRecords: "载入中...",
                sInfoThousands: ",",
                oPaginate: {
                    sFirst: "首页",
                    sPrevious: "上页",
                    sNext: "下页",
                    sLast: "末页"
                },
                oAria: {
                    sSortAscending: ": 以升序排列此列",
                    sSortDescending: ": 以降序排列此列"
                }
            },
            // 禁用自动调整列宽
            autoWidth: false,
            // 为奇偶行加上样式，兼容不支持CSS伪类的场合
            stripeClasses: ["odd", "even"],
            // 取消默认排序查询,否则复选框一列会出现小箭头
            order: [],
            // 隐藏加载提示,自行处理
            processing: false,
            // 启用服务器端分页
            serverSide: true,
            // 禁用原生搜索
            searching: false
        },
        COLUMN: {
            // 复选框单元格
            CHECKBOX: function (idName, checked, title, IsFilter) {
                var item= {
                    className: "td-checkbox",
                    orderable: false,
                    bSortable: false,
                    data: idName,
                    "mData":idName,
                    type: "checkbox",
                    IsFilter:IsFilter?true:false,
                   // "title": '<div class="i-checks"><label> <input type="checkbox" class="thead checkall" title="全选" /></label></div>',
               
                    render: function (data, type, row, meta) {
                     
                        var content = '<div class="i-checks ' + (checked  ? "checkField" : "checkItem") + '"><label>';
                        content += '	<input type="checkbox" class=" " value="' + row[idName] + '" ' + (checked && row[idName] ? "checked" : "") + '/>';
                        content += '	<span></span>';
                        content += '</label></div>';
                        return content;
                    }
                };
                if (checked)
                {
                    item.title = title;
                }
                //if (sWidth && sWidth!="") {
                //    item.sWidth = sWidth;
                //}
                return item;
            },
            LASTMODIFYDATE: {
                        "data ": "LastModifyDate",
                        "name": "LastModifyDate",
                        "title": "修改时间",
                        "sDefaultContent": "",
                        "type": "date",
                        IsFilter:true,
                        render: function (data, type, row) {
                            return row.LastModifyDate;
                        }
                    },
            ACTIONBTN:function(idName,url,buttons){
                return {
                    "mData": idName,
                    "name": "",
                     data: idName,
                    "title": "操作",
                    //"sWidth": "10%",//定义列宽度，以百分比表示
                    "sDefaultContent": "",
                    orderable: false,
                    "bSortable": false,
                    render: function (data, type, row, meta) {
                        
                        var content = '<a class=\"btn btn-info  btn-rounded  btn-outline\"  href="' + url + '?id=' + row[idName] + '" title="编辑" ><i class="fa fa-paste"></i></a>';
                        if (buttons != null && buttons.length > 0) {
                            for (var i = 0; i < buttons.length; i++) {
                                if (i == 0) {
                                    content = '<a class="btn btn-info btn-circle  btn-rounded  btn-outline btn-table-item-event ' + buttons[i].cssClass + '" event="' + i + '" id="' + row[buttons[i].data] + '" ' + (buttons[i].url && buttons[i].url != "" ? ' href="' + buttons[i].url + "?id=" + row[idName] +'"' : "") + ' title="' + buttons[i].name + '" ><i class="fa ' + buttons[i].icon + '"></i></a>';
                                }
                                else {
                                    content += '<label > &nbsp;</label><a class=\"btn btn-info btn-circle btn-rounded  btn-outline btn-table-item-event' + buttons[i].cssClass + '\" event="' + i + '" id="' + row[buttons[i].data] + '"' + (buttons[i].url && buttons[i].url != "" ? ' href="' + buttons[i].url + '?id=' + row[idName] +'"': '') + '" title="' + buttons[i].name + '" ><i class="fa ' + buttons[i].icon + '"></i></a>';
                                }
                            }
                        }
                        else {
                          
                        }
                        // 

                        return content;
                    }
                };
            }
          
        },
        // 回调
        CALLBACKS: {
            // 表格绘制前的回调函数
            PREDRAWCALLBACK: function (settings) {
                if (settings.oInit.scrollX == '100%') {
                    // 给表格添加css类，处理scrollX : true出现边框问题
                    $(settings.nTableWrapper).addClass('dataTables_DTS');
                }
            },
            INITCOMPLETE: function (settings, json) {
                if (settings.oInit.scrollX == '100%' && $(settings.nTable).parent().innerWidth() - $(settings.nTable).outerWidth() > 5) {
                    $(settings.nScrollHead).children().width('100%');
                    $(settings.nTHead).parent().width('100%');
                    $(settings.nTable).width('100%');
                }
            },
            // 表格每次重绘回调函数
            DRAWCALLBACK: function (settings) {
                if ($(settings.aoHeader[0][0].cell).find(':checkbox').length > 0) {
                    // 取消全选
                    $(settings.aoHeader[0][0].cell).find(':checkbox').prop('checked', false);
                }
                // 高亮显示当前行
                $(settings.nTable).find("tbody tr").click(function (e) {
                    $(e.target).parents('table').find('tr').removeClass('warning');
                    $(e.target).parents('tr').addClass('warning');
                });
            }
        },
        // 常用render可以抽取出来，如日期时间、头像等
        RENDER: {
            ELLIPSIS: function (data, type, row, meta) {
                data = data || "";
                return '<span title="' + data + '">' + data + '</span>';
            }
        }

    }

};

(function ($) {
    $.fn.CustomForm = function (options) {
        var isValidate = options.isValidate;
        var isTable = options.isTable;
        var options = $.extend({}, $.fn.CustomForm.defaults, options);
       
        if (options.isValidate) {
            $.fn.CustomForm.Validate(this, options);
            $.fn.CustomForm.Remote(this, options);
        }
    
        if (options.Init) {
         
            $.fn.CustomForm.InitForm(this, options);
        }
        if (options.isTable) {
           return $.fn.CustomForm.Table(this, options);
        }

        
        return this;
    }
   
    $.fn.CustomForm.defaults = {
        isValidate: true,
        isTable: false,
        Init:true
    }
    $.fn.CustomForm.InitForm = function (form, options) {
        if (form.find(".touchspin3").TouchSpin) {
            form.find(".touchspin3").each(function () {
                var _self = $(this);
                form.find(".touchspin3").TouchSpin({
                    verticalbuttons: true,
                    max:parseInt(_self.attr("max")),
                    min: 1,
                    buttondown_class: 'btn btn-white',
                    buttonup_class: 'btn btn-white'
                });
            });
           
        }

        if (form.find('.select2').select2) {
            form.find('.select2').select2({ width: "100%" });
        }
        if (form.find('.i-checks').iCheck) {
            form.find('.i-checks').iCheck({
                checkboxClass: 'icheckbox_square-green',
                radioClass: 'iradio_square-green',
            });
        }
        if ($('.datetimepicker').datepicker) {
            $('.datetimepicker').datepicker({
                format: 'yyyy-mm-dd',
                language: 'zh-CN',
            }).on('changeDate', function () {
                $(this).datepicker('hide');
            });
        }
        if ($('.summernote').summernote) {
            $('.summernote').each(function () {
                var _self = $('.summernote');
               var $summernote = _self.summernote({
                    height: 250,
                    minHeight: 250,
                    lang: 'zh-CN',
                    focus: true,
                    popover: {
                        air: [
                                ['color', ['color']],
                                ['font', ['bold', 'underline', 'clear']]
                        ]
                    },
                    callbacks: {
                        onImageUpload: function (files) {
                            var formData = new FormData();
                            formData.append("file", files[0]);
                            formData.append("typeno", _self.attr("data-typeno"));
                            $.ajax({
                                url: "/attach/api/Summernote",//路径是你控制器中上传图片的方法，下面controller里面我会写到
                                data: formData,
                                cache: false,
                                contentType: false,
                                processData: false,
                                type: 'POST',
                                success: function (result) {
                                    $summernote.summernote('insertImage', result.Data, function ($image) {
                                        $image.attr('src', result.Data);
                                    });
                                }
                            });

                        }
                    }
                });
            });
        }
        if ($(".select2-region-group").hasClass("select2-region-group"))
        {
            $(".select2-region-group").each(function () {
                InitRegion($(this));
            });
        }
        

    }
    //初始化表单验证
    $.fn.CustomForm.Validate = function (form, options) {
            try {
                var rule = {};
                //,.radioboxlist[validate],.checkboxlist[checkboxlist]
                form.find("input[validate],textarea[validate],select[validate]").each(function () {
                    var name = ($(this).attr("key") ? $(this).attr("key") : $(this).attr("name"));
                    rule[name] = eval("(" + $(this).attr("validate") + ")");
                });
                options = $.extend({
                    onKeyup: true,
                    onsubmit: true,
                    meta: "validate",
                    rules: rule,
                    ignore: options.ignore ? options.ignore : ".ignore",
                    errorPlacement: function (lable, element) {
                        var ele = element.parent().parent();
                        if (ele.hasClass("input-group")) {
                            ele.parent().addClass("has-error");
                            ele.parent().find(".field-validation-valid").html(lable.html());
                        }
                        else {
                            ele.addClass("has-error");
                            ele.find(".field-validation-valid").html(lable.html());
                        }
                    },
                    success: function (lable, element) {

                        var ele = $("#" + lable.attr("for")).parent().parent();
                       
                        if (ele.hasClass("has-error")) {
                            ele.removeClass("has-error");
                        }
                        if (ele.hasClass("input-group")) {
                            ele.parent().removeClass("has-error");
                            ele.parent().find(".field-validation-valid").html("");
                        }
                        else {
                            ele.removeClass("has-error");
                            ele.find(".field-validation-valid").html("");
                        }


                    }

                }, options || {});
                var vaild = form.validate(options);
                return vaild;
            }
            catch (e) {
                alert(e);
                return false;
            }
    }
    $.fn.CustomForm.Remote = function (form, options) {
        form.find("input[data-remote]").each(function () {
            $(this).blur(function () {
                var _input = $(this);
                if (form.validate().element(_input)) {
                    if (_input.attr("data-remote") != "") {
                        var remoteJson = eval("(" + _input.attr("data-remote") + ")");
                        var param = {};
                        param[_input.attr("name")] = _input.val();
                        Ajax({
                            url: remoteJson["url"],
                            data: param,
                            IsNoLoad: true,
                            success: function (result) {
                            },
                            error: function (data) {
                                var ele = _input.parent().parent();
                                ele.addClass("has-error");
                                if (ele.hasClass("control-new")) {
                                    if (ele.parent().hasClass("input-group")) {
                                        ele.parent().next(".field-validation-valid").html(remoteJson.msg);
                                    }
                                    else
                                        ele.parent().find(".field-validation-valid").html("");
                                }
                                else {
                                    if (ele.hasClass("input-group")) {
                                        ele.next(".field-validation-valid").html(remoteJson.msg);
                                    }
                                    else
                                        ele.find(".field-validation-valid").html("");
                                }
                            }

                        });
                    }
                }
            });
        });
    }
    $.fn.CustomForm.Table = function (table, options)
    {
    
        table.find("thead>tr>td>div.i-checks,tfoot>tr>td>div.i-checks").iCheck({
            checkboxClass: 'icheckbox_square-green',
            radioClass: 'iradio_square-green',
        }).on("ifChanged", function (event) {
            if (event.target.checked) {
                if ($(event.target).hasClass("thead")) {
                    table.find("tfoot>tr>td>div.i-checks").iCheck("check");
                }
                else {
                    table.find("thead>tr>td>div.i-checks").iCheck("check");
                }
                table.find("tbody>tr>td>div.checkItem").iCheck("check");
            }
            else {
                if ($(event.target).hasClass("thead")) {
                    table.find("tfoot>tr>td>div.i-checks").iCheck("uncheck");
                }
                else {
                    table.find("thead>tr>td>div.i-checks").iCheck("uncheck");
                }
            
                table.find("tbody>tr>td>div.checkItem").iCheck("uncheck");
            }
        });
        var queryColumns = [];
       
        $.each(options.columns, function (index, item) {
            console.log(item);
            if(item.IsFilter)
            {
                if (!item.filter) {
                    text = item.type;
                    switch (text) {
                        case "":
                            text = "text";
                            break;
                        case "string":
                            text = "text";
                            break;
                        case "int":
                            text = "number";
                            break;
                    }
                }
                else {
                    text = item.filter.type;
                }
                queryColumns.push( { name: item.name,
                    display:item.title,
                    type: text,
                    editor:{type:text},
                    value: item.filter ? item.filter.value : ""
                });
            }
        });
        var queryData;
        /*
         * 初始化表格参数
         */
        var oTable = table.dataTable($.extend({
            order: [],
            // 启用服务器端分页
            serverSide: true,
            // 禁用原生搜索
            searching: false,
            //是否开启本地分页
            "paging": true,
            deferRender: true,
            // 禁用自动调整列宽
            autoWidth: false,
            "lengthMenu": [20, 50, 100, 200],
            // 为奇偶行加上样式，兼容不支持CSS伪类的场合
            stripeClasses: ["even", "odd"],
            "processing": true,
            //开关，指定当当前列在排序时，是否增加classes 'sorting_1', 'sorting_2' and 'sorting_3'，打开后，在处理大数据时，性能有所损失
            bSortClasses: false,
            responsive: true,
            oLanguage: {
                sProcessing: "处理中...",
                sLengthMenu: "显示 _MENU_ 项结果",
                sZeroRecords: "没有匹配结果",
                sInfo: "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
                sInfoEmpty: "显示第 0 至 0 项结果，共 0 项",
                sInfoFiltered: "(由 _MAX_ 项结果过滤)",
                sInfoPostFix: "",
                sSearch: "搜索:",
                searchPlaceholder: "关键字搜索",
                sUrl: "",
                sEmptyTable: "表中数据为空",
                sLoadingRecords: "载入中...",
                sInfoThousands: ",",
                oPaginate: {
                    sFirst: "首页",
                    sPrevious: "上页",
                    sNext: "下页",
                    sLast: "末页"
                },
                oAria: {
                    sSortAscending: ": 以升序排列此列",
                    sSortDescending: ": 以降序排列此列"
                }
            },
            "drawCallback": function (oSettings) {
                table.find("tbody").find('.checkItem,.checkField').iCheck({
                    checkboxClass: 'icheckbox_square-green',
                    radioClass: 'iradio_square-green',
                });
                table.find("tbody").find('a.btn-table-item-event').on("click", function () {
                    if (options.actionClick) {
                        options.actionClick($(this));
                    }
                });
                table.find("tbody").find('.checkField').iCheck("disable");
                table.find("tbody").find('a.btn-delete').click(function () {
                    var id = $(this).attr("id");
                    if (!id || id == "") {
                        return;
                    }
                    Notify.Confirm("您确认要删除该信息吗?", "确认提示", function () {
                        Ajax({
                            url: options.deleteUrl,
                            data: { deleteKeys: id },
                            success: function (data) {
                                oTable.fnPageChange(0);
                            }
                        });
                    });
                });
            },
            /*
             * 向服务器传递的参数
             */
            //"fnServerParams": function (data) {
            //    data.LocalName = $("#LocalName").val();
            //    data.RouteUrl = $("#RouteUrl").val();
            //},
            ajax: {
                type: "POST",
                url: options.ajaxUrl,
                // 传入已封装的参数
                data: function (data) {
                    data.pageIndex = data.start / data.length + 1;
                    data.pageSize = data.length;
                    data.sortName = (data.order.length > 0 ? data.columns[data.order[0].column].name : data.columns[1].name);
                    data.sortOrder = (data.order.length > 0 ? data.order[0].dir : "desc");
                    data.Group = queryData;
                    // 右上角搜索
                    //data.keyword = data.search.value;
                    delete data.search;
                    delete data.columns;
                },
                dataType: "json",
                dataSrc: function (result) {
                    // 后台不实现过滤功能，每次查询均视作全部结果
                    //if (result.ret != 0) {
                    //    bootboxAlert({message : '获取数据失败：' + result.msg});
                    //}
                    // result.data.rhavs = result.data.rhavs || {};
                    if (!result.IsError) {
                        result.recordsTotal = result.Data.Total || 0;
                        result.recordsFiltered = result.Data.Total || 0;
                        //result.data = result.data.rhavs || [];
                        //delete result.data.totalCount;
                        //delete result.data.rhavs;
                        return result.Data.Rows;
                    }
                    else {
                        Notify.Error(result.Message);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {

                    //bootboxAlert({
                    //    message : '获取列表失败：' + getAjaxErrorResponseContent(XMLHttpRequest, textStatus, errorThrown)
                    //});
                }
            }


        }, options));
       
        $("body").find("form[datatable='" + table.attr("id") + "']").find(".btn-delete").click(function () {
            var deleteitems = table.find(".checkItem>label>.checked>input[type='checkbox']");
            if (deleteitems.length <= 0) {
                Notify.Error("请选择您要删除的项", "错误提示");
                return;
            }
            var deleteKeys = "";
            var i = 0;
            deleteitems.each(function () {
                if (i > 0) {
                    deleteKeys += ",";
                }
                deleteKeys += $(this).attr("value");
                i++;
            });
            Notify.Confirm("您确认要删除该信息吗?", "确认提示", function () {
                Ajax({
                    url: options.deleteUrl,
                    data: { deleteKeys: deleteKeys },
                    success: function (data) {
                        oTable.fnPageChange(0);
                    }
                });
                return true;
            });

        });
        $("body").find("form[datatable='" + table.attr("id") + "']").find(".btn-search").click(function () { oTable.fnPageChange(0); });
        
        $("body").find("form[datatable='" + table.attr("id") + "']").find(".btn-query-filter").click(function () {

            var filter = QSFilter.InitFilter(table.attr("id"), queryColumns, function (data) { queryData = data; oTable.fnPageChange(0); });
            if (queryData && queryData.op) {
                filter.setData(queryData);
            }
            else {
                filter.addRule($(filter.RuleContainer.children(":eq(0)")));
            }
          
        });
        return oTable;
    }
    $.fn.TableSelectRow=function()
    {
        var deleteitems = this.find(".checkItem>label>.checked>input[type='checkbox']");
        var deleteKeys = "";
        var i = 0;
        deleteitems.each(function () {
            if (i > 0) {
                deleteKeys += ",";
            }
            deleteKeys += $(this).attr("value");
            i++;
        });
        return deleteKeys;
    }
})(jQuery);
///ajax 方法
var Ajax = function (options) {
    $.ajax({
        cache: false,
        async: true,
        url: options.url,
        data: options.data,
        dataType: 'json',
        type: 'POST',
        timeout: 100000,
        contentType: 'application/x-www-form-urlencoded',
        beforeSend: function () {
         
        },
        complete: function (xhr, textStatus) {

            if (xhr.responseText && xhr.responseText != null && xhr.responseText.indexOf("The return URL specified for request redirection is invalid.") != -1) {
                window.location.href = window.location.href;
            }
            if (options.complete) {
                options.complete(xhr, textStatus, options);
            }

        },
        success: function (result) {
           
            if (!result) return;

            if (!result.IsError) {
                if (options.success) {
                    options.success(result.Data, result.Message);
                }
            }
            else {
                if (options.error)
                    options.error(result.Message);
                else {
                    Notify.Error(result.Message);
                }
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            Notify.Error(errorThrown);
        }

    });
};
var FormHelper =
{
    //获取表单的直
    getFormData: function (from) {
        var data = {};

        from.find("select").each(function () {
            var fN = $(this).attr("name");
            if (!fN || fN == "") {
                fN = $(this).attr("Id");
            }
            else {
                data[fN] = $(this).val();
            }
        });
        from.find("textarea").each(function () {
            var fN = $(this).attr("name");
            if (!fN || fN == "") {
                fN = $(this).attr("Id");
            }
            else {
                data[fN] = $(this).val();
            }
        });
        from.find("input").each(function () {
            var fN = $(this).attr("name");
            if (!fN || fN == "") {
                fN = $(this).attr("Id");
            }
            else if ($(this).attr("type") == "checkbox") {
                data[fN] = $(this)[0].checked;
            }

            else {
                data[fN] = $(this).val();
            }
        });
        from.find(".i-checks>label>.checked>input").each(function () {
            var fN = $(this).attr("name");
            if (!fN || fN == "") {
                fN = $(this).attr("Id");
            }
            else if ($(this).attr("type") == "checkbox") {
                data[fN] = true;
            }

        });

        return data;
    },
    ajaxSubmit: function (frm, func) {
        if (!frm.valid()) {
            return false;
        }
        var dataFrm = FormHelper.getFormData(frm);
        Ajax({
            url: frm.attr("action"),
            data: dataFrm,
            success: function (result) {
                if (func) {
                    func(result);
                }
                else {
                    Notify.alert("保存成功");
                }
            }
        });

    }
};
var Notify =
{
    Guid: function () {
        function G() {
            return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
        }
        return (G() + G() + "-" + G() + "-" + G() + "-" +
             G() + "-" + G() + G() + G());
    },
    defaults: {
        id: "",
        Title: "信息提示",
        content: "",
        buttons: []
    },
    alert: function (content, title) {
        this.Init({
            id: this.Guid(),
            Title: title ? title : "信息提示",
            content: content,
        });
    },
    Success: function (content, title) {
        this.Init({
            id: this.Guid(),
            Title: title ? title : "成功提示",
            content: '<a class="btn btn-primary btn-circle " ><i class="fa fa-check"></i></a>' + content,
        });
    },
    Error: function (content, title) {
        this.Init({
            id: this.Guid(),
            Title: title ? title : "错误提示",
            content: '<a class="btn btn-danger btn-circle " ><i class="fa fa-times"></i></a>' + content,
        });
    },
    Warning: function (content, title) {
        this.Init({
            id: this.Guid(),
            Title: title ? title : "系统警告",
            content: '<a class="btn btn-warning btn-circle" ><i class="fa fa-times"></i></a>' + content,
        });
    },
    loading: function (content) {
        return this.Init({
            id: this.Guid(),
            Title: "",
            content: '<i class="fa fa-spinner fa-spin pull-left"></i>' + ((content && content != "") ? content : "数据加载中，请耐心等待"),
        });
    },
    Confirm: function (content, title, func, closefuncClick) {
        var modal = this.Init({
            id: this.Guid(),
            Title: title ? title : "确认提示",
            content: content,
            buttons: [
                {
                    id: "close", isClose: true, Name: "关闭", click:function() {
                        if (closefuncClick) {
                            closefuncClick();
                            modal.remove();
                        }
                    },
                },
                {
                    id: "btnConfirm", isClose: false, Name: "确定", click: function () {
                        func();
                        return true;
                    }
                },
            ]
        });
    },
    Info: function (options) {
        this.Init(options);
    },
    Remote: function (options) {
        options = $.extend(this.defaults, options);
        options.id = Notify.Guid();
        var mode = ' <div class="modal inmodal in" id="' + options.id + '" role="dialog"  aria-hidden="true">';
        mode += ' <div class="modal-dialog modal-lg" role="document">';
        mode += '<div class="modal-content ui-widget-content ui-draggable">';
        mode += '<div class="modal-header">';
        mode += ' <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>';
        mode += '<p class="modal-title text-left" style="color:#575757;font-size: 20px;font-weight: 600;">' + options.Title + '</p4>';
        mode += ' </div>';
        mode += '<div class="modal-body">';
        mode += '</div>';
        mode += '</div>';
        mode += '</div>';
        mode += '</div>';
        $("body").append(mode);
        var modal = $("#" + options.id);

        //if (options.modalClass && options.modalClass != "")
        //{
        //    modal.find(".modal-content").addClass(options.modalClass);
        //}
       
        
        modal.modal({
            backdrop: 'static',
            keyboard: true,
            remote: options.remote
        }).on("loaded.bs.modal", function () {
            // modal.find(".modal-body").css({ "overflow": "auto" });
            var html = "";
            if (options.buttons != null && options.buttons.length > 0) {
                for (var i = 0; i < options.buttons.length; i++) {
                    if (options.buttons[i].isClose) {
                        html += '<button type="button" class="btn btn-white btn-close" data-dismiss="modal">' + options.buttons[i].Name + '</button>';
                    }
                    else {
                        html += '<button type="button" id="' + options.buttons[i].id + '" class="btn ' + (options.buttons[i].cssClass ? options.buttons[i].cssClass : "") + ' ">' + options.buttons[i].Name + '</button>';
                    }
                }
                modal.find(".modal-footer").append(html);
                modal.find(".modal-footer>button").click(function () {
                    var btn = $(this);
                    if (!$(this).hasClass("btn-close")) {
                        for (var i = 0; i < options.buttons.length; i++) {
                            if (btn.attr("id") == options.buttons[i].id) {
                                if (options.buttons[i].click(modal, options.id, options.buttons[i])) {
                                    modal.modal("hide");
                                }
                            }
                        }
                    }
                });
            }
            modal.find(".select2,.ajax-select").on("select2:open", function () { $(".select2-container--open").css({ "z-index": "9999" }); });
            modal.find(".modal-header").addClass("ui-widget-header");
            modal.find(".ui-draggable").draggable({
                handle: '.ui-widget-header'
            });
            if (options.loaded) {
                options.loaded(modal, options.id);
            }
            //var modalHeight = ($(window).height() - $('#' + options.id + ' .modal-dialog').height()) / 2;
            //var modalWidth = ($(window).width() - $('#' + options.id + ' .modal-dialog').width()) / 2;
            //$(this).find('.modal-dialog').css({
            //    "width": $(window).width(),
            //    "height": $(window).height(),
            //});
            //$(this).find('.modal-dialog').css({
            //    'margin-left': modalWidth,
            //    'margin-top': modalHeight
            //});
        }).on('show.bs.modal', function (e) {
            // 关键代码，如没将modal设置为 block，则$modala_dialog.height() 为零
            // $(this).css('display', 'block');
            var modalHeight = ($(window).height() - $('#' + options.id + ' .modal-dialog').height()) / 2;
            var modalWidth = ($(window).width() - $('#' + options.id + ' .modal-dialog').width()) / 2;

            $(this).find('.modal-dialog').css({
                'margin-left': modalWidth,
                'margin-top': modalHeight
            });
        }).on('hidden.bs.modal', function () {

            modal.removeData("bs.modal");
            modal.remove();
        });

    },
    Init: function (options) {
        //options = $.extend(this.defaults, options);
        if (!options.id) {
            options.id = this.Guid();
        }
        var mode = ' <div class="modal inmodal fade" id="' + options.id + '"  role="dialog"  aria-hidden="true">';
        mode += '<div class="modal-dialog ' + (!options.MinWidthShow ? "modal-sm" : "") + '">';
        mode += '<div class="modal-content ui-widget-content ui-draggable">';
        if (options.Title && options.Title != "") {
            mode += '<div class="modal-header ui-widget-header">';
            mode += ' <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>';
            mode += '<p class="modal-title text-left" style="color:#575757;font-size:20px;font-weight: 600;">' + options.Title + '</p4>';
            mode += ' </div>';
        }
        mode += '<div class="modal-body nalert" style="color:#797979;">';
        mode += options.content;
        mode += '</div>';
        if (options.buttons != null && options.buttons.length > 0) {
            mode += '<div class="modal-footer">';

            for (var i = 0; i < options.buttons.length; i++) {
                if (options.buttons[i].isClose) {
                    mode += '<button type="button" class="btn btn-white btn-close" data-dismiss="modal">' + options.buttons[i].Name + '</button>';
                }
                else {
                    mode += '<button type="button" id="' + options.buttons[i].id + '" class="btn btn-primary ' + (options.buttons[i].cssClass ? options.buttons[i].cssClass : "") + ' ">' + options.buttons[i].Name + '</button>';
                }
            }
            mode += '</div>';
        }
        mode += '</div>';
        mode += '</div>';
        mode += '</div>';

        $("body").append(mode);
        var modal = $("#" + options.id);
        if (!options.isHide) {
            modal.modal("show");
        }
        modal.find(".ui-draggable").draggable({
            handle: '.ui-widget-header'
        });
        modal.on('shown.bs.modal', function (e) {
            // 关键代码，如没将modal设置为 block，则$modala_dialog.height() 为零
            $(this).css('display', 'block');
            var modalHeight = ($(window).height() - $('#' + options.id + ' .modal-dialog').height()) / 2;
            $(this).find('.modal-dialog').css({
                'margin-top': modalHeight
            });
        })
            .on('hidden.bs.modal', function () {
                var removeFlag = true;
                if (options.buttons && options.buttons.length > 0) {
                    $.each(options.buttons, function (index, item) {
                        if (item.id == "close") {
                            if (item.click) {
                                item.click(item);
                                removeFlag = false;
                            }

                            return false;
                        }
                    });
                }
                if (removeFlag) {
                    modal.remove();
                }

            });
        modal.find(".modal-footer>button").click(function () {
            var btn = $(this);
            if (!$(this).hasClass("btn-close")) {
                for (var i = 0; i < options.buttons.length; i++) {
                    if (btn.attr("id") == options.buttons[i].id) {
                        if (options.buttons[i].click(btn)) {
                            modal.modal("hide");
                        }
                    }
                }
            }

        });
        return modal;
    }
};
$(function () {
    $(document).ready(function () {//系统信息初始化
        if ($(".dropdown-alerts").hasClass("dropdown-alerts")) {

            Ajax({
                url: "/api/MyToDoList",
                type: 'POST',
                success: function (result) {
                    var html = "";
                    if (result != null && result.Rows.length > 0) {
                        for (var i = 0; i < result.Rows.length; i++) {
                            html += "<li>";
                            html += ' <a href="javascript://">';
                            html += '<div>';
                            html += '<i class="fa fa-tasks fa-fw"></i> ' + result.Rows[i].Title ;
                            html += '<span class="pull-right text-muted small">' + result.Rows[i].ProcessId + '</span>';
                            html += '</div>';
                            html += ' </a>';
                            html += "</li>";
                            html += '<li class="divider"></li>';
                            if (i >= 4)
                            {
                                break;
                            }
                        }
                        if (result.Rows.length > 5) {
                            html += '<li>';
                            html += '<div class="text-center link-block">';
                            html += '<a href="/member/mytask">';
                            html += '<strong>所有代办事项</strong>';
                            html += '<i class="fa fa-angle-right"></i>';
                            html += '</a>';
                            html += '</div>';
                            html += '</li>';
                        }
                    }
                    if ($(".my-todo-list").hasClass("my-todo-list"))
                    {
                        var todolist = "";
                        if (result != null && result.Rows.length > 0) {
                            for (var i = 0; i < result.Rows.length; i++) {
                                todolist += "<tr>";
                                todolist += '<td><a href="#"><small>' + result.Rows[i].ProcessId + "&nbsp;&nbsp;" + result.Rows[i].Title + '</small></a></td>';
                                todolist += '<td><i class="fa fa-clock-o"></i> ' + result.Rows[i].SendDate + '</td>';
                                todolist += '</tr>';
                                if (i >= 7) {
                                    break;
                                }
                            }
                            if (result.Rows.length >8) {
                                todolist += "<tr>";
     
                                todolist += '<td colspan="2" class="text-right"><a href="/member/mytask">更多>></a></td>';
                                todolist += '</tr>';
                            }
                        }
                        $(".my-todo-list").children("tbody").html(todolist);
                    }
                    $(".dropdown-alerts").parent().find(">a>.label-warning").html(result.Total);
                    $(".dropdown-alerts").html(html);
                }
            });
        }
        if ($(".dropdown-messages").hasClass("dropdown-messages")) {
            Ajax({
                url: "/api/MyNotify",
                type: 'POST',
                data: {status:0},
                success: function (result) {
                    var html = "";
                    $(".dropdown-messages").html(html);
                    if (result != null && result.Rows.length > 0) {
                        for (var i = 0; i < result.Rows.length; i++) {
                            html += "<li>";
                            html += '<a class="notify-wait-user-msg-item" href="javascript://" style="padding:3px;"  id="' + result.Rows[i].NotifyId + '">';
                            html += '<div class="dropdown-messages-box">';
                           
                            html += '<img alt="image" class="img-circle pull-left" src="/api/avatar/' + result.Rows[i].SenderUserId + '">';
                            
                            html += '<div class="media-body" style="padding-left:5px;">';
                           // html += '<small class="pull-right">46h ago</small>';
                            html += '<strong>' + result.Rows[i].SenderName + ':' + result.Rows[i].Title + '</strong><br />' + result.Rows[i].Content + ' <br /> ';
                            html += '<small class="text-muted">' + result.Rows[i].SendDate + '</small>';
                            html += '</div>';
                            html += '</div>';
                            html += '</a>';
                            html += "</li>";
                            html += '<li class="divider"></li>';

                           
                            if (i >= 4) {
                                break;
                            }
                        }
                        if ($(".feed-activity-list").hasClass("feed-activity-list")) {
                            var message = "";
                            if (result != null && result.Rows.length > 0) {
                                for (var i = 0; i < result.Rows.length; i++) {
                                    message += ' <div class="feed-element ">';
                                    message += '<a class="notify-wait-user-msg-item" href="javascript://" style="padding:3px;display:block;" id="' + result.Rows[i].NotifyId + '">';
                                    message += '<img alt="image" class="img-circle pull-left" src="/api/avatar/' + result.Rows[i].SenderUserId + '">';
                                    message += ' <div class="media-body"  style="padding-left:5px;">';
                                    //message += ' <small class="pull-right text-navy">1m ago</small>';
                                    message += ' <strong>' + result.Rows[i].SenderName + ':' + result.Rows[i].Title + '</strong>';
                                    message += '<div>' + result.Rows[i].Content + '</div>';
                                    message += ' <small class="text-muted">' + result.Rows[i].SendDate + '</small>';
                                    message += '</div>';
                                    message += '</a>';
                                    message += '</div>';


                                }

                            }
                            $(".feed-activity-list").html(message);
                        }
                        if (result.Rows.length > 5) {
                            html += '<li>';
                            html += '<div class="text-center link-block">';
                            html += '<a href="/member/mynotify">';
                            html += '<i class="fa fa-envelope"></i> <strong>所有消息</strong>';
                            html += '</a>';
                            html += '</div>';
                            html += '</li>';
                        }
                        $(".dropdown-messages").html(html);
                        $(".notify-wait-user-msg-item").on("click", function () {
                            var _self = $(this);
                            if (_self.attr("id"))
                            {
                                Ajax({
                                    url: "/api/readernotify",
                                    data: { notifyid: _self.attr("id") },
                                    success: function (result) {
                                        var total = $(".dropdown-messages").parent().find(">a>.label-primary");
                                        total.html( parseInt(total.text()) - 1);
                                        $(".notify-wait-user-msg-item[id='" + _self.attr("id") + "']").parent().remove();
                                    }
                                });
                            }
                        });
                    }
                    $(".dropdown-messages").parent().find(">a>.label-primary").html(result.Total);
                   
                }
            });
        }
        $(".ui-draggable").draggable({
            handle: '.ui-widget-header'
        });
       
    });
 
});
///socket msg show
function insertMsg(result) {
    if (result.Content == "open") {
        return false;
    }
    var msgContent = $(".socket-message-content");
    var html = '<div class="feed-element" id="socket-message-id">';
    html += '<img alt="image" class="img-circle pull-left" src="/api/avatar/' + result.SenderId + '">';
    html += ' <div class="media-body">';
    html += '<small class="pull-right"></small>';
    html += '<strong>' + result.SenderName + '</strong>';
    html += '<div>' + result.Content + '</div>';
    html += '<small class="text-muted">' + result.SenderDate + '</small>';
    html += ' </div>';
    html += '</div>';
    msgContent.prepend(html);
  //msgContent[0].scrollTop = msgContent[0].scrollHeight;
}

/**
初始化socket
*/
function InitSocket(websocket)
{
    if ($(".socket-chart").hasClass("socket-chart")) {

        websocket.Connect();
        $(".socket-chart").find(".select2").select2({
            width: "100%",
            delay: 250,
            minimumInputLength: 1,
            ajax: {
                url: '/api/GetUsers',
                dataType: 'json',
                type: 'post',
                data: function (params) {
                    return {
                        keyword: params.term,    //接收搜索框输入的姓名
                        page: params.page
                    };
                },
                processResults: function (data, params) {        //data返回数据
                    params.page = params.page || 1;
                    for (var i = 0; i < data.Data.Rows.length; i++) {
                        data.Data.Rows[i].id = data.Data.Rows[i].UserId;
                        data.Data.Rows[i].text = data.Data.Rows[i].RealName;
                    }
                    return {
                        results: data.Data.Rows,
                        pagination: {
                            more: (params.page * 10) < data.Data.Total
                        }
                    };
                },
                cache: true
            },
            placeholder: "输入姓名 或者邮箱 或者手机号搜索...",
            allowClear: true,    //选中之后，可手动点击删除
            escapeMarkup: function (markup) { return markup; }, // 字符转义处理自定义格式化防止xss注入
            templateResult: function (repo) {
                var markup = "";

                markup += "<div class='select2-result-repository clearfix'>" +
    "<div class='select2-result-repository__avatar col-md-3' style='padding:0;margin-top:10px;'><img  class='img-circle' src='/api/avatar/" + repo.UserId + "' style='width:40px;height:40px;' /></div>" +
    "<div class='select2-result-repository__meta col-md-9' style='padding:0'>" +
    "<div class='select2-result-repository__title'><span class='btn btn-primary btn-circle' style='width:10px;height:10px;padding:0;" + (repo.IsOnline ? "" : "background:#d4d4d4") + "' ></span>" + repo.RealName + "</div>";


                markup += "<div class='select2-result-repository__statistics'>" +
                  "<div class='select2-result-repository__forks'><i class='fa fa-mobile'></i> " + repo.Phone + " </div>" +
                  "<div class='select2-result-repository__stargazers'><i class='fa fa-envelope'></i> " + repo.Email + " </div>" +
                  //"<div class='select2-result-repository__watchers'><i class='fa fa-eye'></i> " + repo.UserId + "</div>" +
                "</div>" +
                "</div></div>";


                return markup;

            }, // 函数用来渲染结果
            templateSelection: function (repo) {
                $(".socket-chart").find("#Receiver").val(JSON.stringify({ "UserId": repo.UserId ,"UserName":repo.UserName,"RealName":repo.UserName}));
                return repo.text;

            } // 函数用于呈现当前的选择
        });

        $(".socket-chart").find(".btn-sendMessage").click(function () {
            var receiver = $(".socket-chart").find("#Receiver").val();
            if (!receiver || receiver == "") {
                Notify.Error("请选择接收人");
                return false;
            }
            var user = eval("(" + receiver + ")");
            if (!user) {
                return false;
            }
            var content = $(".socket-chart").find("#txtcontent").val();
            $(".socket-chart").find("#txtcontent").val("");
            if (!content || content == "") {
                return false;
            }
            insertMsg({
                SenderId: "",
                SenderName: "自己",
                Content: content,
                SenderDate: new Date().format("yyyy-MM-dd HH:mm:ss")
            });
            websocket.Send(user.UserId, content);

        });
    }

}

///获取系统当前日期时间
Date.prototype.format = function (format) {
    var o = {
        "M+": this.getMonth() + 1, //month 
        "d+": this.getDate(), //day 
        "h+": this.getHours(), //hour 
        "m+": this.getMinutes(), //minute 
        "s+": this.getSeconds(), //second 
        "q+": Math.floor((this.getMonth() + 3) / 3), //quarter 
        "S": this.getMilliseconds() //millisecond 
    }
    if (format.indexOf("H") != -1) {
        o = {
            "M+": this.getMonth() + 1, //month 
            "d+": this.getDate(), //day 
            "H+": this.getHours(), //hour 
            "m+": this.getMinutes(), //minute 
            "s+": this.getSeconds(), //second 
            "q+": Math.floor((this.getMonth() + 3) / 3), //quarter 
            "S": this.getMilliseconds() //millisecond 
        }
    }

    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
};

var QSFilter = {
    RuleContainer: null,
    fields: [],
    editorCounter: 0,
    gridId: "",
    ModalDialog: null,
    strings: {
        "and": "并且",
        "or": "或者",
        "equal": "相等",
        "notequal": "不相等",
        "startwith": "以..开始",
        "endwith": "以..结束",
        "like": "相似",
        "greater": "大于",
        "greaterorequal": "大于或等于",
        "less": "小于",
        "lessorequal": "小于或等于",
        "in": "包括在...",
        "notin": "不包括...",
        "addgroup": "增加分组",
        "addrule": "增加条件",
        "deletegroup": "删除分组"
    },
    //operators: ["equal", "notequal", "greater", "greaterorequal", "less", "lessorequal"],
    operators: {
        text: ["equal", "notequal", "startwith", "endwith", "like", "greater", "greaterorequal", "less", "lessorequal", "in", "notin"],
        number: ["equal", "notequal", "greater", "greaterorequal", "less", "lessorequal", "in", "notin"],
        checkbox: ["equal", "notequal"],
        date: ["equal", "notequal", "greater", "greaterorequal", "less", "lessorequal"],
        select: ["equal", "notequal", "startwith", "endwith", "like", "greater", "greaterorequal", "less", "lessorequal", "in", "notin"]
    },
    editors: {
        text: {
            create: function (container, field) {
                var input = $("<input type='text' class='form-control' name='" + field.name + "_query' id='" + field.name + "_query' />");

                var div = $('<div class="form-group"></div>').append(input);
                container.append(div);
                if (field.value) {
                    input.val(field.value);
                }
                return input;
            },
            setValue: function (input, value) {
                input.val(value);
            },
            getValue: function (input) {
                return input.val();
            },
            destroy: function (input) {
                input.val('');
            }
        },
        select: {
            create: function (container, field) {
                var input = $("<input type='text' class='form-control' name='" + field.name + "_query' id='" + field.name + "_query' />");

                var div = $('<div class="form-group"></div>').append(input);
                container.append(div);
                if (field.value) {
                    input.val(field.value);
                }
                return input;
            },
            setValue: function (input, value) {
                input.val(value);
            },
            getValue: function (input) {
                return input.val();
            },
            destroy: function (input) {
                input.val('');
            }
        },
        date: {
            create: function (container, field) {
                var input = $("<input type='text' class='form-control datetimepicker'  name='" + field.name + "_query' id='" + field.name + "_query' />");
                var div = $('<div class="form-group"></div>').append(input);
                container.append(div);
                input.datepicker({
                    format: 'yyyy-mm-dd',
                    language: 'zh-CN',
                }).on('changeDate', function () {
                    $(this).datepicker('hide');
                });
                // input.ligerDateEditor(field.editor.options || {});
                return input;
            },
            setValue: function (input, value) {
                input.val(value);
            },
            getValue: function (input, field) {
                return input.val();
            },
            destroy: function (input) {
                input.val('');
            }
        },
        number: {
            create: function (container, field) {
                var input = $("<input type='number' class='form-control'  name='" + field.name + "_query' id='" + field.name + "_query'/>");
                var div = $('<div class="form-group"></div>').append(input);
                container.append(div);

                return input;
            },
            setValue: function (input, value) {
                input.val(value);
            },
            getValue: function (input, field) {
                var isInt = field.type == "int";
                if (isInt)
                    return parseInt(input.val(), 10);
                else
                    return parseFloat(input.val());
            },
            destroy: function (input) {
                input.val('');
            }
        },
        checkbox: {
            create: function (container, field) {
                var input = $('<div class="i-checks "> <label for="' + field.name + '"_query"> <input tabindex="9" id="' + field.name + '_query" name="' + field.name + '_query" type="checkbox"> </label>');

                var div = $('<div class="form-group"></div>').append(input);
                container.append(div);
                input.iCheck({
                    checkboxClass: 'icheckbox_square-green',
                    radioClass: 'iradio_square-green',
                });
                return input;
            },
            setValue: function (input, value) {
                if (input.hasClass("i-checks ")) {
                    if (value) {
                        input.find("label>div.icheckbox_square-green").addClass("checked");
                        input.find("input").attr("checked", value);
                    }
                    else {
                        input.removeClass("checked");
                        input.find("input").removeAttr("checked", value);
                    }
                }
                else {
                    if (value) {
                        input.attr("checked", value);
                    }
                    else {
                        input.removeAttr("checked", value);
                    }
                }


            },
            getValue: function (input, field) {

                if (input.hasClass("i-checks ")) {
                    return input.find("label>div.icheckbox_square-green").hasClass("checked");
                }
                else {
                    return input[0].checked;
                }
            },
        }
        //select: {
        //    create: function (container, field) {
        //        var input = $("<select class='select2'  name='" + field.name + "_query' id='" + field.name + "_query'></select>");

        //        var div = $('<div class="form-group"></div>').append(input);
        //        container.append(input);
        //        input.select2({ });
        //        return input;
        //    },
        //    setValue: function (input, value) {
        //        input.val(value);
        //        input.trigger("change");
        //    },
        //    getValue: function (input) {
        //        return input.val();
        //    },
        //    destroy: function (input) {
        //        input.val('');
        //    }
        //}
    },
    InitFilter: function (id, fields, func) {
        this.fields = fields;
        if (!fields || fields.length <= 0) {
            Notify.Error("请先配置需要搜索的列");
            return;
        }
        var g = this;
        this.gridId = id;
        if (!$("#" + id + "_where_filter").find(".query-grid-where-filter").hasClass("query-grid-where-filter")) {
            this.ModalDialog = Notify.Init({
                id: id + "_where_filter",
                Title: "高级查询",
                isHide: true,//初始化隐藏
                MinWidthShow: true,//是否固定宽度
                content: "<div class='query-grid-where-filter'></div>",
                buttons: [
                    {
                        id: "close", isClose: true, Name: "关闭", click:function() {

                        }
                    },
                    {
                        id: "btnConfirm", isClose: false, Name: "确定", click: function () {
                            if (func) {
                                func(QSFilter.getData());
                            }
                            return true;
                        }
                    }
                ]
            });
            container = this.ModalDialog.find(".query-grid-where-filter");
            this.RuleContainer = container;
        }
        container.html("");

        g.addGroup(container.children(":eq(0)"));
        container.append(this._bulidGroupTableHtml(false, false));
        container.children("table").addClass("l-filter-group-frist");
        $(container).find(".addgroup,.deletegroup,.addrule,.deleterole").on("click", function (e) {
            var e = this;
            var cn = $(this).attr("class");

            if (cn.indexOf("addgroup") >= 0) {
                var jtable = $(this).parent().parent().parent().parent().parent();
                g.addGroup(jtable);
            }
            else if (cn.indexOf("deletegroup") >= 0) {
                var jtable = $(this).parent().parent().parent().parent().parent();
                g.deleteGroup(jtable);
            }
            else if (cn.indexOf("addrule") >= 0) {
                var jtable = $(this).parent().parent().parent().parent().parent();
                g.addRule(jtable);
            }
            else if (cn.indexOf("deleterole") >= 0) {
                var rulerow = $(this).parent().parent();
                g.deleteRule(rulerow);
            }
        });

        this.ModalDialog.modal("show");
        return this;
    },
    addGroup: function (jgroup) {
        var g = this;
        jgroup = $(jgroup || g.group);
        var lastrow = $(">tbody:first > tr:last", jgroup);
        var groupHtmlArr = [];
        groupHtmlArr.push('<tr class="l-filter-rowgroup"><td class="l-filter-cellgroup" colSpan="4">');
        var altering = !jgroup.hasClass("l-filter-group-alt");
        groupHtmlArr.push(g._bulidGroupTableHtml(altering, true));
        groupHtmlArr.push('</td></tr>');
        var row = $(groupHtmlArr.join(''));
        lastrow.after(row);
        row.find(".addgroup,.deletegroup,.addrule,.deleterole").on("click", function (e) {
            var e = this;
            var cn = $(this).attr("class");

            if (cn.indexOf("addgroup") >= 0) {
                var jtable = $(this).parent().parent().parent().parent().parent();
                g.addGroup(jtable);
            }
            else if (cn.indexOf("deletegroup") >= 0) {
                var jtable = $(this).parent().parent().parent().parent().parent();
                g.deleteGroup(jtable);
            }
            else if (cn.indexOf("addrule") >= 0) {
                var jtable = $(this).parent().parent().parent().parent().parent();
                g.addRule(jtable);
            }
            else if (cn.indexOf("deleterole") >= 0) {
                var rulerow = $(this).parent().parent();
                g.deleteRule(rulerow);
            }
        });
        return row.find("table:first");
    },
    //删除分组 
    deleteGroup: function (group) {
        var g = this;
        $("td.l-filter-value", group).each(function () {
            var rulerow = $(this).parent();
            $("select.fieldsel", rulerow).unbind();
            g.removeEditor(rulerow);
        });
        $(group).parent().parent().remove();
    },
    //增加一个条件
    //parm [jgroup] 分组的jQuery对象
    addRule: function (jgroup) {
        var g = this;
        jgroup = jgroup || g.group;
        var lastrow = $(">tbody:first > tr:last", jgroup);
        var rulerow = $(g._bulidRuleRowHtml());
        lastrow.after(rulerow);
        if (g.fields.length) {
            //如果第一个字段启用了自定义输入框
            g.appendEditor(rulerow, g.fields[0]);
        }

        //事件：字段列表改变时
        $("select.fieldsel", rulerow).bind('change', function () {
            var jopsel = $(this).parent().parent().next().find("select:first");
            var fieldName = $(this).val();
            if (!fieldName) return;
            var field = g.getField(fieldName);
            //字段类型处理
            var fieldType = field.type;
            var oldFieldtype = rulerow.attr("fieldtype");
            if (fieldType != oldFieldtype) {
                jopsel.html(g._bulidOpSelectOptionsHtml(fieldType));
                rulerow.attr("fieldtype", fieldType);
            }


            //当前的编辑器
            var editorType = null;
            //上一次的编辑器
            var oldEditorType = rulerow.attr("editortype");
            editorType = field.editor.type;

            if (oldEditorType) {
                //如果存在旧的输入框 
                g.removeEditor(rulerow);
            }
            if (editorType) {
                //如果当前选择的字段定义了输入框
                g.appendEditor(rulerow, field);
            } else {
                rulerow.removeAttr("editortype").removeAttr("editorid");

                $("td.l-filter-value:first", rulerow).html("<div class='form-group'><input type='text' class='form-control valtxt'  name='" + field.name + "_query' id='" + field.name + "_query'/></div>");
            }
        });
        rulerow.find(".deleterole").on("click", function (e) {
            var e = this;
            var cn = e.className;
            if (cn.indexOf("deleterole") >= 0) {
                var rulerow = $(e).parent().parent();
                g.deleteRule(rulerow);
            }
        });
        return rulerow;
    },

    //删除一个条件
    deleteRule: function (rulerow) {
        $("select.fieldsel", rulerow).unbind();
        this.removeEditor(rulerow);
        $(rulerow).remove();
    },
    //生成分组的html
    _bulidGroupTableHtml: function (altering, allowDelete) {
        var g = this;
        var tableHtmlArr = [];
        tableHtmlArr.push('<table cellpadding="0" cellspacing="0" border="0" class="l-filter-group');
        if (altering)
            tableHtmlArr.push(' l-filter-group-alt');
        tableHtmlArr.push('"><tbody>');
        tableHtmlArr.push('<tr class="l-filter-rowlast"><td class="l-filter-rowlastcell" align="right" colSpan="4">');
        //and or

        tableHtmlArr.push('<div data-toggle="buttons-checkbox" class="btn-group">');
        if (!allowDelete) {
            tableHtmlArr.push('<button  class="btn btn-primary btn-sm addgroup">' + g.strings['addgroup'] + '</button>');
        }
        tableHtmlArr.push('<button  class="btn btn-primary btn-sm addrule">' + g.strings['addrule'] + '</button>');
        //tableHtmlArr.push('<ul class="dropdown-menu">');
        //tableHtmlArr.push('<li class="addgroup"><a href="javascript://" >' + g.strings['addgroup'] + '</a></li>');
        //tableHtmlArr.push('<li class="addrule"><a href="javascript://">' + g.strings['addrule'] + '</a></li>');

        if (allowDelete)
            tableHtmlArr.push('<button  class="btn btn-primary btn-sm deletegroup">' + g.strings['deletegroup'] + '</button>');


        ////add group
        //tableHtmlArr.push('<button type="button" class="btn btn-primary btn-rounded addgroup">' + g.strings['addgroup'] + '</button>');
        ////add rule
        //tableHtmlArr.push('<button type="button" class="addrule">' + g.strings['addrule'] + '</button>');
        //if (allowDelete)
        //    tableHtmlArr.push('<button type="button"  class="deletegroup">' + g.strings['deletegroup'] + '</button>');

        tableHtmlArr.push('</div>');
        tableHtmlArr.push('<div class="form-group"><select class="groupopsel">');
        tableHtmlArr.push('<option value="and">' + g.strings['and'] + '</option>');
        tableHtmlArr.push('<option value="or">' + g.strings['or'] + '</option>');
        tableHtmlArr.push('</select></div>');
        tableHtmlArr.push('</td></tr>');

        tableHtmlArr.push('</tbody></table>');
        return tableHtmlArr.join('');
    },

    //生成字段值的html
    _bulidRuleRowHtml: function (fields) {
        var g = this;
        fields = g.fields;
        var rowHtmlArr = [];
        var fieldType = fields[0].type;
        rowHtmlArr.push('<tr fieldtype="' + fieldType + '"><td class="l-filter-column">');
        rowHtmlArr.push('<div class="form-group"><select class="fieldsel ">');
        for (var i = 0, l = fields.length; i < l; i++) {
            var field = fields[i];
            rowHtmlArr.push('<option value="' + field.name + '"');
            if (i == 0) rowHtmlArr.push(" selected ");
            rowHtmlArr.push('>');
            rowHtmlArr.push(field.display);
            rowHtmlArr.push('</option>');
        }
        rowHtmlArr.push("</select></div>");
        rowHtmlArr.push('</td>');

        rowHtmlArr.push('<td class="l-filter-op">');
        rowHtmlArr.push('<div class="form-group"><select class="opsel">');
        rowHtmlArr.push(g._bulidOpSelectOptionsHtml(fieldType));
        rowHtmlArr.push('</select></div>');
        rowHtmlArr.push('</td>');
        rowHtmlArr.push('<td class="l-filter-value">');

        rowHtmlArr.push("<div class='form-group'><input type='text' class='form-control valtxt'  name='" + field.name + "_query' id='" + field.name + "_query'/></div>");
        rowHtmlArr.push('</td>');
        rowHtmlArr.push('<td>');
        rowHtmlArr.push('<div class="deleterole"><i class="fa fa-close" ></i></div>');
        rowHtmlArr.push('</td>');
        rowHtmlArr.push('</tr>');
        return rowHtmlArr.join('');
    },
    //删除编辑器
    removeEditor: function (rulerow) {
        var g = this;
        var type = $(rulerow).attr("editortype");
        var id = $(rulerow).attr("editorid");
        // var editor = g.editors[id];
        // if (editor) g.editors[type].destroy(editor);
        $("td.l-filter-value:first", rulerow).html("");
    },

    //获取一个运算符选择框的html
    _bulidOpSelectOptionsHtml: function (fieldType) {

        var ops = this.operators[fieldType];
        if (!ops || !ops.length) {
            ops = this.operators[fieldType];
        }

        var opHtmlArr = [];
        for (var i = 0, l = ops.length; i < l; i++) {
            var op = ops[i];
            opHtmlArr[opHtmlArr.length] = '<option value="' + op + '">';
            opHtmlArr[opHtmlArr.length] = this.strings[op];
            opHtmlArr[opHtmlArr.length] = '</option>';
        }
        return opHtmlArr.join('');
    },
    //附加一个输入框
    appendEditor: function (rulerow, field) {
        var g = this;
        var cell = $("td.l-filter-value:first", rulerow).html("");

        var editor = g.editors[field.type];
        g.editors[++g.editorCounter] = editor.create(cell, field);
        rulerow.attr("editortype", field.type).attr("editorid", g.editorCounter);

    },
    //获取分组数据
    getData: function (group) {
        var g = this;
        group = group || this.RuleContainer.children("table:eq(0)");

        var groupData = {};

        $("> tbody > tr", group).each(function (i, row) {
            var rowlast = $(row).hasClass("l-filter-rowlast");
            var rowgroup = $(row).hasClass("l-filter-rowgroup");
            if (rowgroup) {
                var groupTable = $("> td:last > table:last", row);
                if (groupTable.length) {
                    if (!groupData.groups) groupData.groups = [];
                    groupData.groups.push(g.getData(groupTable));
                }
            }
            else if (rowlast) {
                groupData.op = $(".groupopsel:first", row).val();
            }
            else {
                var fieldName = $("select.fieldsel:first", row).val();
                var field = g.getField(fieldName);
                var op = $(".opsel:first", row).val();
                var value = g._getRuleValue(row, field);
                var type = $(row).attr("fieldtype") || "string";
                if (!groupData.rules) groupData.rules = [];
                groupData.rules.push({
                    field: fieldName, op: op, value: value, type: type
                });
            }
        });

        return groupData;
    },
    //设置规则
    //parm [group] 分组数据
    //parm [jgruop] 分组table dom jQuery对象
    setData: function (group, jgroup) {
        var g = this;
        jgroup = jgroup || this.RuleContainer.children("table:eq(0)");
        var lastrow = $(">tbody:first > tr:last", jgroup);
        jgroup.find(">tbody:first > tr").not(lastrow).remove();
        $("select:first", lastrow).val(group.op);
        if (group.rules) {
            $(group.rules).each(function () {
                var rulerow = g.addRule(jgroup);
                rulerow.attr("fieldtype", this.type || "string");
                $("select.opsel", rulerow).val(this.op);
                $("select.fieldsel", rulerow).val(this.field).trigger('change');
                var editorid = rulerow.attr("editorid");
                if (editorid && g.editors[editorid]) {
                    var field = g.getField(this.field);
                    if (field && field.editor) {
                        g.editors[field.editor.type].setValue(g.editors[editorid], this.value, field);
                    }
                }
                else {
                    $(":text", rulerow).val(this.value);
                }
            });
        }
        if (group.groups) {
            $(group.groups).each(function () {
                var subjgroup = g.addGroup(jgroup);
                g.setData(this, subjgroup);
            });
        }
    },
    //根据fieldName 获取 字段
    getField: function (fieldname) {
        var g = this;
        for (var i = 0, l = g.fields.length; i < l; i++) {
            var field = g.fields[i];
            if (field.name == fieldname) return field;
        }
        return null;
    },
    _getRuleValue: function (rulerow, field) {
        var g = this;
        var editorid = $(rulerow).attr("editorid");
        var editortype = $(rulerow).attr("editortype");
        var editor = g.editors[editorid];

        if (editor)
            return g.editors[editortype].getValue(editor, field);

        return $(".valtxt:first", rulerow).val();
    },
};